function Validate(tblname,divName)
{
	var theTable = document.getElementById(tblname);
	var inputs = theTable.getElementsByTagName("input");
	var textareas = theTable.getElementsByTagName("textarea");		
	var labels = theTable.getElementsByTagName("label");
	document.getElementById(divName).textContent = "";
	
	for(var i=0;i < inputs.length;i++)
	{
		if(inputs[i].type != "button" && inputs[i].type != "submit" && inputs[i].type != "reset")
		{
			if(inputs[i].type == "text" || inputs[i].type == "password" || inputs[i].type == "textarea")
			{
				var text = inputs[i].value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
				if( text.length == 0 && inputs[i].title != "CanNull" )
				{

					//get labels for alert error
					for(var j=0;j < labels.length;j++)
					{
						if(labels[j].htmlFor == inputs[i].name)
						{
							document.getElementById(divName).textContent = "'" + labels[j].textContent + "'" 
																					+ " can not be EMPTY"	;
							inputs[i].value = "";
							inputs[i].focus();
							return false;
						}
					}
				}	
			}
		}
	}

	for(var i=0 ; i < textareas.length;i++)
	{
		var text = textareas[i].value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
		if(text.length == 0 && textareas[i].title != "CanNull")
		{
			//get labels for alert error
			for(var j=0;j < labels.length;j++)
			{
				if(labels[j].htmlFor == textareas[i].name)
				{
					document.getElementById(divName).textContent = "'" + labels[j].textContent + "'" 
																			+ " can not be EMPTY"	;
					textareas[i].value = "";
					return false;
				}
			}
		}
	}
	
	var result = ValidateDate('startdate','enddate');
	//alert(result);
	if(result == "false")
		return false;
	
	return true;
}

function ValidateDate(dateFName,dateTName)
{
	var dateFvalue = document.getElementsByName(dateFName)[0].value;
	var dateTvalue = document.getElementsByName(dateTName)[0].value;
	if(dateFvalue == null || dateTvalue == null)
		return "false";
	
	var dayF = dateFvalue.substring(0,2);
	var monthF = dateFvalue.substring(3,5);
	var yearF = dateFvalue.substring(6,10);
	var dateFrom = new Date();
	dateFrom.setFullYear(parseInt(yearF),parseInt(monthF),parseInt(dayF));
	

	var dayT = dateTvalue.substring(0,2);
	var monthT = dateTvalue.substring(3,5);
	var yearT = dateTvalue.substring(6,10);
	var dateTo = new Date();
	dateTo.setFullYear(parseInt(yearT),parseInt(monthT),parseInt(dayT));
	
	if(dateFrom > dateTo)
	{
		alert("Sorry ! From Date must be smaller To Date.");
		return "false";
	}
}

function ValidateEmail(fieldName,divName)
{
	document.getElementById(divName).textContent = "";
	if(document.getElementsByName(fieldName)[0].value != "")
	{
		var emailPatt =  /^[^@]+@[^@]+.[a-z]{2,}$/i;
		var emailStr = document.getElementsByName(fieldName)[0].value;
		
		if(emailStr.search(emailPatt) == -1)
		{
			//alert("Invalid Email. Please enter again.");
			document.getElementById(divName).style.color = "red";
			document.getElementById(divName).textContent = "Invalid Email. Please enter again.";
			document.getElementsByName(fieldName)[0].value = "";
			document.getElementsByName(fieldName)[0].style.background = "#FFFF99";
		}
		else
		{
			document.getElementsByName(fieldName)[0].style.background = "#FFFFFF";
		}
	}
}

function CheckEmail(strEmail)
{
    if(strEmail != "")
    {
        var emailPatt =  /^[^@]+@[^@]+.[a-z]{2,}$/i;	
	    if(strEmail.search(emailPatt) == -1) //Invalid
	        return false;
	    else
	        return true;    
	}
}

function ConfirmDelete()
{
	var r=confirm("Are you sure delete this item ?");
	if (r==true) //delete
	  {
	  	return true;
	  }
	else //no delete
	  {
	  	return false;
	  }
}

//java script for AJAX
var oldName = "";
var isIDValid = false;

function waiting(fieldName,servletURL)
{
	isIDValid = false;
	document.getElementById("divIDExist").textContent = "Waiting....";
	setTimeout("CheckNameExist('"+fieldName+"','"+servletURL+"')", 3000);
}

function CheckNameExist(fieldName,servletURL) 
{
   var idField = document.getElementsByName(fieldName)[0];
   
   if(idField.value != oldName && idField.value != "")
   {
	   oldName = idField.value;
	   var url = servletURL + "?username=" + encodeURIComponent(idField.value);
	   if (typeof XMLHttpRequest != "undefined") {
		   req = new XMLHttpRequest();
	   } else if (window.ActiveXObject) {
		   req = new ActiveXObject("Microsoft.XMLHTTP");
	   }
	   req.open("GET", url, true);
	   req.onreadystatechange = callbackValidate;
	   req.send(null);
	   //waiting(fieldName,servletURL);
	   //req.close();
   }
   else
   {
	   isIDValid = false;
   }
}

function callbackValidate() {
if (req.readyState == 4) 
	{
		if (req.status == 200) 
		{
			parseMessage();
		}
	}
}	

function parseMessage() 
{
	 var message = req.responseXML.getElementsByTagName("message")[0];
	 setMessage(message.childNodes[0].nodeValue);
}

function setMessage(message) 
{
	 var userMessageElement = document.getElementById("divIDExist");
	 userMessageElement.textContent = "";
	 var messageText;
	 if (message == "invalid") {
		 isIDValid = false;
		 userMessageElement.style.color = "red";
		 messageText = "This username ' " + oldName + " ' is EXIST.";
	 } else {
		 isIDValid = true;
		 userMessageElement.style.color = "green";
		 messageText = "You can use this name.";
	 }
	 var messageBody = document.createTextNode(messageText);
	 if (userMessageElement.childNodes[0]) {
		 userMessageElement.replaceChild(messageBody,  userMessageElement.childNodes[0]);
	 } else {
		 userMessageElement.appendChild(messageBody);
	 }
}


function ValidateEmail(fieldName,divName)
{
	document.getElementById(divName).textContent = "";
	if(document.getElementsByName(fieldName)[0].value != "")
	{
		var emailPatt =  /^[^@]+@[^@]+.[a-z]{2,}$/i;
		var emailStr = document.getElementsByName(fieldName)[0].value;
		
		if(emailStr.search(emailPatt) == -1)
		{
			//alert("Invalid Email. Please enter again.");
			document.getElementById(divName).style.color = "red";
			document.getElementById(divName).textContent = "Invalid Email. Please enter again.";
			document.getElementsByName(fieldName)[0].value = "";
			document.getElementsByName(fieldName)[0].style.background = "#FFFF99";
		}
		else
		{
			document.getElementsByName(fieldName)[0].style.background = "#FFFFFF";
		}
	}
}

//dinh dang kieu money ',' (ex: 2,000,000.00)
function FormatNumericWithSeparate(field)
{
	var DecimalNumber = 2;
	var DecimalChar = ".";
	var SeperateChar = ",";
	var ValueString = field.value;
	var ValueStringAfterDecimal = "";
	var ValueStringNew = "";
	if (field.value < 0) 
		ValueString = ValueString.substring(1, ValueString.length); //Bo dau tru
	if (ValueString.indexOf(DecimalChar) != -1)
	{
		ValueStringAfterDecimal = ValueString.substring(ValueString.indexOf(DecimalChar), ValueString.indexOf(DecimalChar) + 1 + DecimalNumber) // Tinh luon dau cham
		ValueString = ValueString.substring(0, ValueString.indexOf(DecimalChar))
	}

	if (ValueStringAfterDecimal.indexOf(SeperateChar) != -1)
	{
		alert("Không phải là dữ liệu số!");
		field.value = "";
		field.focus();		
		return;
	}	
	ValueString = ValueString.replace(/,/g,'');
	ValueStringNew = "";
	while (ValueString.length >3)
	{
		ValueStringNew = SeperateChar + ValueString.substring(ValueString.length - 3, ValueString.length) + ValueStringNew;
		ValueString = ValueString.substring(0, ValueString.length - 3);
	}
	if (DecimalNumber != 0)
		ValueStringNew = ValueString + ValueStringNew + ValueStringAfterDecimal;
	else
		ValueStringNew = ValueString + ValueStringNew;

	if (field.value < 0) 
		ValueStringNew = "- " + ValueStringNew;
	
	field.value = ValueStringNew;
}

//dinh dang kieu money ',' (ex: 2,000,000.00)
function FormatNumeric(str)
{
	var DecimalNumber = 2;
	var DecimalChar = ".";
	var SeperateChar = ",";
	var ValueString = str;
	var ValueStringAfterDecimal = "";
	var ValueStringNew = "";
	if (str.length < 0) 
		ValueString = ValueString.substring(1, ValueString.length); //Bo dau tru
	if (ValueString.indexOf(DecimalChar) != -1)
	{
		ValueStringAfterDecimal = ValueString.substring(ValueString.indexOf(DecimalChar), ValueString.indexOf(DecimalChar) + 1 + DecimalNumber) // Tinh luon dau cham
		ValueString = ValueString.substring(0, ValueString.indexOf(DecimalChar))
	}

	if (ValueStringAfterDecimal.indexOf(SeperateChar) != -1)
	{
		alert("Không phải là dữ liệu số!");
		str = "";	
		return;
	}	
	ValueString = ValueString.replace(/,/g,'');
	ValueStringNew = "";
	while (ValueString.length >3)
	{
		ValueStringNew = SeperateChar + ValueString.substring(ValueString.length - 3, ValueString.length) + ValueStringNew;
		ValueString = ValueString.substring(0, ValueString.length - 3);
	}
	if (DecimalNumber != 0)
		ValueStringNew = ValueString + ValueStringNew + ValueStringAfterDecimal;
	else
		ValueStringNew = ValueString + ValueStringNew;

	if (str < 0) 
		ValueStringNew = "- " + ValueStringNew;
	
	str = ValueStringNew;
	return str;
}

function CheckForm(lblError)
{
    $("#error_pnl").fadeOut("fast");
    for(var i = 0 ; i < $("div.required").length ; i++)
    {
        for(var j = 0 ; j < $("div.required:eq(" + i.toString() + ") .text-input").length ; j++ )
        {
            var input = $("div.required:eq(" + i.toString() + ") .text-input:eq(" + j.toString() + ")");
            if( $.trim(input.val()) == "" )
            {
                var title = $.trim(input.parent().children("span").html().replace(":",""));
                lblError.html(title + " không được để trống");
                //$("#error_pnl").show();
                $("#error_pnl").fadeIn("fast");
                input.focus();
                return false;
            }
            else
            {
                if(input.hasClass("email-input") == true)
                {
                    if(CheckEmail($.trim(input.val())) == false) 
                    {
                        lblError.html("Email không hợp lệ.");
                        $("#error_pnl").fadeIn("fast");
                        input.select();
                        input.focus();
                        return false;
                    }
                }
                
                if(input.hasClass("number-input") == true)
                {
                    if( isNaN($.trim(input.val())) )
                    {
                        lblError.html("Dữ liệu phải là số. Vui lòng nhập lại.");
                        $("#error_pnl").fadeIn("fast");
                        input.select();
                        input.focus();
                        return false;
                    }
                }
            }
        }
    }
    return true;
}
function CheckFormat_HHMM(field)
{
	if (field.value == "" )
	{
		return
	}
	
	var err = 0;	
	var Err1 = "Chuỗi thời gian không hợp lệ.";	
			
	var strValue = field.value;	
	var strValue1
	var strValue2
	var strValue3
	
		
	if (strValue.length < 4)
		err = 1;
	else 
	{
			strValue1 = strValue.substr(0,2);

			if (strValue.length = 4)
				strValue3 = strValue.substr(2,2);
			if (strValue.length >= 5)
				strValue3 = strValue.substr(3,2);
	}
		
	if (isNaN (strValue1))
		err = 1;
	else
		if (parseInt(strValue1) < 0 || parseInt(strValue1) >= 24)
			err =1; 
		
	if (isNaN (strValue3))
		err = 1;
	else
		if (parseInt(strValue3) < 0 || parseInt(strValue3) > 59)
			err =1; 	

	if (err != 0 )
	{
		alert(Err1);
		field.focus();
		field.value = "";
	}
	else
		field.value = strValue1 + ":" + strValue3;
}